//
//  QRCodeViewController.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/16.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController,UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate {

    @IBOutlet weak var tabBar: UITabBar!
    
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    // 扫描图像的view
    @IBOutlet weak var scanlineImgView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 设置默认选中二维码页面
        tabBar.selectedItem = tabBar.items![0] as? UITabBarItem
    }

    @IBAction func closeBtn(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        // 冲击波动画
        barAnimation()
        
        // 开始扫描
        scan()
    }
    
    // 冲击波动画
    private func barAnimation(){
        
        topConstraint.constant = -heightConstraint.constant
        view.layoutIfNeeded()
        UIView.animateWithDuration(2.0){
            // 设置动画运行状态
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.topConstraint.constant = 300
            self.view.layoutIfNeeded()
        }
    }
    
    // tabBar代理方法
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
        println(item.tag)
        // 根据选项 调整扫描卡大小
        heightConstraint.constant = item.tag == 0 ? widthConstraint.constant : widthConstraint.constant * 0.5
        // 停止动画 再中心启动动画 可以让动画根据最新的约束执行动画
        self.scanlineImgView.layer.removeAllAnimations()
        // 启动动画
        barAnimation()
    }
    
    // MARK: - 二维码扫描
    // 拍摄会话
    lazy var session : AVCaptureSession = {
        return AVCaptureSession()
    }()
    
    // 输入设备
    lazy var videoInput : AVCaptureDeviceInput? = {
        let devise = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        if devise == nil {
         return nil
        }
        
        return AVCaptureDeviceInput(device: devise, error: nil)
    }()
    
    // 输出设备
    lazy var dataOutPut : AVCaptureMetadataOutput = {
        return AVCaptureMetadataOutput()
    }()
    
    // 预览图层
    lazy var previewLayer : AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer.frame = self.view.bounds
        return layer
        }()

    lazy var drawLayer : CALayer = {
       let layer = CALayer()
        layer.frame = self.view.bounds
        return layer
    }()
    
    // 开始扫描
    private func scan(){
        if !session.canAddInput(videoInput) {
            println("无法添加输入设备")
            return
        }
        
        // 能否添加输出设备
        if !session.canAddOutput(dataOutPut){
            println("无法添加输出设备")
            return
        }
        
        // 添加输入设备
        session.addInput(videoInput)
        
        // 添加输出设备
        session.addOutput(dataOutPut)
        
        // 输出设备支持的格式
        println(dataOutPut.availableMetadataObjectTypes)
        
        // 设置输出识别的格式  以及 代理
        dataOutPut.metadataObjectTypes = dataOutPut.availableMetadataObjectTypes
        dataOutPut.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
        // 启动会话
        session.startRunning()
        // 添加预览图层
        view.layer.insertSublayer(drawLayer, atIndex: 0)
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        
        
    }
    
    // 输出设备的代理方法
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
//        println(metadataObjects)
        // 清空图层
        clearDrawLayer()
        for codeObject in metadataObjects {
            if let obj = codeObject as? AVMetadataMachineReadableCodeObject {
                let object = previewLayer.transformedMetadataObjectForMetadataObject(obj) as! AVMetadataMachineReadableCodeObject
                println(object)
                
                drawcornes(object)
            }
        }
    }
    
    // 清除绘图的子图层
    private func clearDrawLayer(){
        // 判断是否有子图层   不加判断会出错
        if drawLayer.sublayers == nil {
            return
        }
        
        // 循环便利删除子图层
        for i in drawLayer.sublayers {
            i.removeFromSuperlayer()
        }
    }
    
    // 绘制边线
    private func drawcornes(codeObject : AVMetadataMachineReadableCodeObject){
        //
        if codeObject.corners.count == 0 {
            return
        }
        
        // 专门用来画图的图层
        let layer = CAShapeLayer()
        // 边线颜色
        layer.strokeColor = UIColor.greenColor().CGColor
        // 填充颜色
        layer.fillColor = UIColor.clearColor().CGColor
        layer.lineWidth = 2
        // 设置路径
        layer.path = createPath(codeObject.corners).CGPath
        
        // 绘图
        drawLayer.addSublayer(layer)
    }
    
    private func createPath(points : NSArray) -> UIBezierPath {
        let path = UIBezierPath()
        // 移动到第一个点
        var point = CGPoint()
        var index = 0
        // 移动到第一个点
        CGPointMakeWithDictionaryRepresentation(points[index++] as! CFDictionaryRef, &point)
        path.moveToPoint(point)
        
        // 循环遍历剩下的点
        while index < points.count {
            CGPointMakeWithDictionaryRepresentation(points[index++] as! CFDictionaryRef, &point)
            path.addLineToPoint(point)
        }
        
        // 关闭路径
        path.closePath()
        
        return path
    }
    
    
}
